package system

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/system"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SystemConfigEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewSystemConfigEditLogic - 新增/修改系统配置
func NewSystemConfigEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemConfigEditLogic {
	return &SystemConfigEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SystemConfigEditLogic) SystemConfigEdit(req *types.SystemConfigEditRequest) error {
	// 创建实例
	configDao := system.NewSystemConfigDao(l.ctx, l.svcCtx)

	// 组装参数
	configInfo := &ent.HzSystemConfig{
		SystemKey:         req.SystemKey,
		SystemValue:       req.SystemValue,
		SystemDescription: req.SystemDescription,
		UpdateAt:          time.Now().Unix(),
	}

	// 新增版本信息
	if req.Type == constant.Add {
		configInfo.CreatedAt = time.Now().Unix()

		// 写入mysql
		if err := configDao.SystemConfigCreate(configInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("mysql 添加配置信息失败: %v", err))
		}

		// 写入redis
		err := l.svcCtx.BizRedis.Hset(constant.HzAdminSystemConfigKey, req.SystemKey, req.SystemValue)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("redis 添加配置信息失败: %v", err))
		}
	}

	// 编辑版本信息
	if req.Type == constant.Edit && req.Id != 0 {
		configInfo.ID = int(req.Id)

		// mysql编辑
		if err := configDao.SystemConfigUpdate(configInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("mysql 修改配置信息失败: %v", err))
		}

		// 写入redis
		err := l.svcCtx.BizRedis.Hset(constant.HzAdminSystemConfigKey, req.SystemKey, req.SystemValue)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("redis 添加配置信息失败: %v", err))
		}
	}

	return nil
}
